<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
    >
      <el-form-item label="采购日期" prop="purchaseDate">
        <el-date-picker
            v-model="formData.purchaseDate"
            type="date"
            value-format="x"
            placeholder="选择采购日期"
            :readonly="formType === 'devState'"
        />
      </el-form-item>
      <el-form-item label="设备固有编号" prop="devId">
        <el-input v-model="formData.devCodeIntrinsic" :readonly="formType === 'devState'" placeholder="请输入设备固有编号" />
      </el-form-item>
      <el-form-item label="设备医院编号" prop="devId">
        <el-input v-model="formData.devCodeHosp" :readonly="formType === 'devState'" placeholder="请输入设备医院编号" />
      </el-form-item>
      <el-form-item label="设备科室编号" prop="devId">
        <el-input v-model="formData.devCodeDept" :readonly="formType === 'devState'" placeholder="请输入设备科室编号" />
      </el-form-item>
      <el-form-item label="分类名" prop="category">
        <el-select v-model="formData.category" placeholder="请选择分类名" @change="categoryChanged" :disabled="formType === 'devState'">
          <el-option
              v-for="dict in categoryOptions"
              :key="dict.value as string"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-select v-model="formData.brand" placeholder="请选择品牌" @change="brandChanged" :disabled="formType === 'devState'">
          <el-option
              v-for="dict in brandOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-select v-model="formData.model" placeholder="请选择型号" :disabled="formType === 'devState'">
          <el-option
              v-for="dict in modelOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item v-if="formType !== 'create'" label="状态" prop="state">
        <el-radio-group v-if="formType === 'devState'" v-model="formData.state">
          <el-radio key="0" :value="0"> 空闲中 </el-radio>
          <el-radio key="5" :value="5"> 已领取 </el-radio>
          <el-radio key="10" :value="10"> 已装机 </el-radio>
          <el-radio key="20" :value="20"> 已遗失 </el-radio>
          <el-radio key="30" :value="30"> 待维修 </el-radio>
          <el-radio key="30" :value="40"> 维修中 </el-radio>
          <el-radio key="40" :value="50"> 已报废 </el-radio>
        </el-radio-group>
        <span v-else>{{tranlateDevState(formData.state)}}</span>
      </el-form-item>

      <el-form-item label="备注" prop="devId">
        <el-input v-model="formData.comment" placeholder="请输入设备备注" />
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {getStrDictOptions, DICT_TYPE, DictDataType} from '@/utils/dict'
import {DeviceApi, DeviceVO, DevModelApi, OptionsVO} from '@/api/ecg/devmanage'

/** 设备 表单 */
defineOptions({ name: 'DeviceForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<DeviceVO>({
  id: 0,
  devId: '',
  purchaseDate: new Date().getTime(),
  devCodeIntrinsic: '',
  devCodeHosp: '',
  devCodeDept: '',
  category: '',
  brand: '',
  model: '',
  comment: '',
  state: 0,
})

const formRules = reactive({
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceApi.getDevice(id)
      const bandData = await DevModelApi.getBrandOption(formData.value.category!)
      brandOptions.value = bandData
      const modelData = await DevModelApi.getModelOption(formData.value.category!, formData.value.brand!)
      modelOptions.value = modelData
    } finally {
      formLoading.value = false
    }
  } else {  // 新增时
    if (categoryOptions.value.length !== 0) {
      formData.value.category = categoryOptions.value[0].value as string
      categoryChanged()
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DeviceVO
    if (formType.value === 'create') {
      await DeviceApi.createDevice(data)
      message.success(t('common.createSuccess'))
    } else if (formType.value === 'update') {
      await DeviceApi.updateDevice(data)
      message.success(t('common.updateSuccess'))
    } else {
      await DeviceApi.updateDeviceState(data)
      message.success(t('common.updateStateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: 0,
    devId: '',
    purchaseDate: new Date().getTime(),
    devCodeIntrinsic: '',
    devCodeHosp: '',
    devCodeDept: '',
    category: '',
    brand: '',
    model: '',
    comment: '',
    state: 0,
  }
  formRef.value?.resetFields()
}

const categoryOptions = ref<DictDataType[]>([])
const brandOptions = ref<OptionsVO[]>([])
const modelOptions = ref<OptionsVO[]>([])

const categoryChanged = async () => {
  const data = await DevModelApi.getBrandOption(formData.value.category!)
  brandOptions.value = data

  formData.value.brand = brandOptions.value.length === 0 ? "" : brandOptions.value[0].value
  brandChanged()
}

const brandChanged = async () => {
  const data = await DevModelApi.getModelOption(formData.value.category!, formData.value.brand!)
  modelOptions.value = data

  formData.value.model = modelOptions.value.length === 0 ? "" : modelOptions.value[0].value
}

const tranlateDevState = (state) => {
  if (state === 0) return "空闲";
  else if (state=== 5) return "已领用";
  else if (state=== 10) return "已装机";
  else if (state=== 20) return "已遗失";
  else if (state=== 30) return "待维修";
  else if (state=== 40) return "维修中";
  else if (state=== 50) return "已报废";
}

onMounted( async () => {
  console.info("onMount DeviceForm...")
  const data = await getStrDictOptions(DICT_TYPE.ECG_DEV_CATEGORY)
  categoryOptions.value = data
})

</script>